#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
已验证测试模块运行器
只运行已验证的测试模块
"""

import sys
import unittest
from io import StringIO
from datetime import datetime

# 添加项目根目录到路径
from pathlib import Path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 导入已验证的测试模块
from test_core import *
from test_time_sync import *
from test_pipeline import *
from test_quality_system import *
from test_enhanced_checkpoint import *
from test_sync_validator import *

def main():
    """主函数"""
    print("开始运行已验证的测试模块...")
    print(f"项目根目录: {project_root}\n")

    # 定义要运行的测试模块
    test_modules = [
        ("核心模块 (test_core)", sys.modules["test_core"]),
        ("时间同步系统 (test_time_sync)", sys.modules["test_time_sync"]),
        ("流水线系统 (test_pipeline)", sys.modules["test_pipeline"]),
        ("质量系统 (test_quality_system)", sys.modules["test_quality_system"]),
        ("增强断点 (test_enhanced_checkpoint)", sys.modules["test_enhanced_checkpoint"]),
        ("同步验证器 (test_sync_validator)", sys.modules["test_sync_validator"]),
    ]

    # 结果统计
    total_tests = 0
    total_success = 0
    total_failures = 0
    total_errors = 0
    results = {}

    # 运行每个测试模块
    for module_name, test_module in test_modules:
        if test_module is None:
            print(f"\n跳过模块: {module_name} (未找到)")
            continue

        print(f"\n{'=' * 80}")
        print(f"运行模块: {module_name}")
        print('=' * 80)

        # 创建测试套件
        loader = unittest.TestLoader()
        suite = loader.loadTestsFromModule(test_module)

        # 创建测试结果收集器
        stream = StringIO()
        runner = unittest.TextTestRunner(
            stream=stream,
            verbosity=2,
            buffer=True,
        )

        # 运行测试
        result = runner.run(suite)

        # 统计结果
        tests_run = result.testsRun
        failures = len(result.failures)
        errors = len(result.errors)
        success = tests_run - failures - errors

        total_tests += tests_run
        total_success += success
        total_failures += failures
        total_errors += errors

        results[module_name] = {
            'tests': tests_run,
            'success': success,
            'failures': failures,
            'errors': errors,
            'success_rate': (success / max(tests_run, 1)) * 100,
        }

        # 输出结果摘要
        print(f"\n{module_name} 测试结果:")
        print(f"  总计: {tests_run}")
        print(f"  成功: {success}")
        print(f"  失败: {failures}")
        print(f"  错误: {errors}")
        print(f"  成功率: {results[module_name]['success_rate']:.2f}%")

    # 生成最终报告
    print("\n" + "=" * 80)
    print("最终测试报告")
    print("=" * 80)
    print(f"执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"\n总体统计:")
    print(f"  总测试数: {total_tests}")
    print(f"  成功: {total_success}")
    print(f"  失败: {total_failures}")
    print(f"  错误: {total_errors}")
    print(f"  成功率: {(total_success / max(total_tests, 1)) * 100:.2f}%")

    print(f"\n各模块详情:")
    print("-" * 80)
    for module_name, result in results.items():
        status = "✓ PASS" if result['failures'] == 0 and result['errors'] == 0 else "✗ FAIL"
        print(f"\n{module_name}: {status}")
        print(f"  测试数量: {result['tests']}")
        print(f"  成功: {result['success']}")
        print(f"  失败: {result['failures']}")
        print(f"  错误: {result['errors']}")
        print(f"  成功率: {result['success_rate']:.2f}%")

    print("\n" + "=" * 80)

    # 返回退出码
    if total_success == total_tests:
        print("\n🎉 所有已验证测试通过! (100% 成功率)")
        return 0
    else:
        print(f"\n⚠️  部分测试失败. 成功率: {(total_success / max(total_tests, 1)) * 100:.2f}%")
        return 1

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)
